using UnityEngine;

namespace Fusion.Utilities.Singleton
{
    public class SingletonBehaviour<T> : MonoBehaviour where T : SingletonBehaviour<T>
    {
        protected static T instance;
        protected static readonly object lockObject = new object();

        protected static bool persistent = true;

        private static bool inited = false;

        public static T Instance {
            get
            {
                if (instance == null && !inited)
                {
                    lock (lockObject)
                    {
                        if (instance == null && !inited)
                        {
                            GameObject singletonObject = new GameObject(typeof(T).Name);
                            instance = singletonObject.AddComponent<T>();
                            instance.Initializate();
                            if (persistent)
                            {
                                DontDestroyOnLoad(singletonObject);
                            }
                            inited = true;
                        }
                    }
                }
                return instance;
            }
        }


        public virtual void Initializate()
        {

        }

        private void OnDestroy()
        {
            if (!persistent)
            {
                instance = null;
                inited = false;
            }
        }
    }

}

